package com.xiaomili.halfsugar.utils;

import android.content.Context;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.xiaomili.halfsugar.GsonRequest;
import com.xiaomili.halfsugar.MyImageCache;

/**
 * 使用单例模式创建Volley工具类
 * 1.构造方法私有化;
 * 2.对外提供一个newInstance方法(注意使用同步锁,避免多线程下不安全的问题)
 * Created by 小米粒 on 2016/7/5.
 */
public class VolleyUtils {
    private static VolleyUtils mVolleyUtils;
    private static RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private ImageLoader.ImageCache mImageCache;

    //构造方法私有化

    public ImageLoader getmImageLoader() {
        return mImageLoader;
    }

    private VolleyUtils(Context context) {
        mRequestQueue = Volley.newRequestQueue(context);
        mImageCache = new MyImageCache();
        mImageLoader = new ImageLoader(mRequestQueue, mImageCache);
    }

    //对外提供一个newInstance方法
    public static VolleyUtils newInstance(Context context) {
        if (mVolleyUtils == null) {
            //加上同步锁,避免多程下创建多个实例的问题
            synchronized (VolleyUtils.class) {
                if (mVolleyUtils == null) {
                    mVolleyUtils = new VolleyUtils(context);
                }
            }
        }
        return mVolleyUtils;
    }
    public static <T> GsonRequest<T> newGsonRequest(int method, String url, Response.Listener<T> listener,
                                                    Response.ErrorListener errorlistener, Class<T> clazz) {
        GsonRequest<T> request = new GsonRequest<>(method, url, clazz ,listener, errorlistener);
        mRequestQueue.add(request);
        return request;
    }
}
